/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.gammapeit.ejb.mail;

import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.activation.DataHandler;
import javax.annotation.Resource;
import javax.ejb.Stateless;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

/**
 *
 * @author Mike
 */
@Stateless
public class Mail implements MailLocal {

    @Resource(name = "mail/claroMail")
    private Session mailSession;

    @Override
    public void enviar(List<String> receptores, String mensaje, String asunto) throws MessagingException, UnsupportedEncodingException {
//        String context = FacesContext.getCurrentInstance().getExternalContext().getRequestContextPath();
        String imagenUrl = "http://localhost:8081/AdminSolicitudes/imagenes/claro_logo.png";
        //String imagenUrl = "http://localhost:8080/AdminSolicitudes/imagenes/claro_logo.png";
//        String imagen = ".." + File.separator + context + File.separator + "imagenes" + File.separator + "claro_logo.png";
        Message msg = new MimeMessage(mailSession);
        msg.setFrom(new InternetAddress("adminsolicitudes@claro.com.co"));
        msg.setSubject(asunto);
        for (String u : receptores) {
            msg.setRecipient(
                    Message.RecipientType.TO,
                    new InternetAddress(u));
        }

        // Create your new message part
        BodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setContent(mensaje, "text/html");

        // Create a related multi-part to combine the parts
        MimeMultipart multipart = new MimeMultipart("related");
        multipart.addBodyPart(messageBodyPart);

        // Create part for the image
        messageBodyPart = new MimeBodyPart();

        // Fetch the image and associate to part
//        DataSource fds = new FileDataSource(imagen);
        try {
            messageBodyPart.setDataHandler(new DataHandler(new URL(imagenUrl)));
        } catch (MalformedURLException ex) {
            Logger.getLogger(Mail.class.getName()).log(Level.SEVERE, null, ex);
        }
        messageBodyPart.setHeader("Content-ID", "<memememe>");

        // Add part to multi-part
        multipart.addBodyPart(messageBodyPart);

        msg.setContent(multipart, "text/html");
        Transport.send(msg);
    }
    // Add business logic below. (Right-click in editor and choose
    // "Insert Code > Add Business Method")
}
